package com.hotel.controller.user;

import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hotel.entity.User;
import com.hotel.context.BaseContext;
import com.hotel.dto.UserLoginDTO;

import com.hotel.result.Result;
import com.hotel.service.UserService;
import com.hotel.utils.JwtUtil;
import com.hotel.vo.UserLoginVo;
import com.hotel.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户登录接口")
public class UserController {

    @Autowired
    private UserService userLoginService;

    @ApiOperation("用户登录")
    @GetMapping("/login")
    public UserLoginVo login(@ApiParam ("用户登录信息") UserLoginDTO userLoginDTO){
        //登录
         User login = userLoginService.login(userLoginDTO);

        //生成Jwt
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",login.getName());
        claims.put("userId",login.getId());
        String token = JwtUtil.createJWT(claims);
        return UserLoginVo.builder()
                .username(login.getName())
                .userId(login.getId())
                .token(token)
                .build();
    }
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<String> register(@ApiParam ("用户信息")@RequestBody User user){
        //根据用户身份证获取年龄
        int age = IdcardUtil.getAgeByIdCard(user.getIdNumber());
        if(age<18){return Result.error("用户必须满18岁");}
        //查询是否已存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getIdNumber,user.getIdNumber())
                .eq(User::getPhone,user.getPhone());
        User one = userLoginService.getOne(wrapper);
        if (one == null) {
            return Result.success(userLoginService.save(user)?"注册成功":"注册失败");
        }
        return Result.error("该身份证号已注册");
    }
    /**
     * 获取用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public UserVo getUserInfo(){
        User byId = userLoginService.getById(BaseContext.getCurrentId());
        UserVo user = new UserVo();
        BeanUtils.copyProperties(byId,user);
        return user;
    }
}
